//
//  WmcDownloadManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/7/14.
//

import Alamofire
import CommonCrypto
import Foundation
import Moya
import RxSwift
import SwiftyXMLParser
import YPNetwork

class WmcDownloadManager: NSObject {
    // Internal

    static let shared = WmcDownloadManager()

    func downloadFile(url: String,
                      progress: ((Double) -> Void)? = nil,
                      success: (() -> Void)? = nil,
                      failure: (() -> Void)? = nil)
    {
        log("准备下载：\(url)")
        WmcDownloadManager.shared.progressClosure = progress
        WmcDownloadManager.shared.successClosure = success
        WmcDownloadManager.shared.failureClosure = failure

        var filePath = ""
        let dest: DownloadRequest.Destination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("video_cache.mp4")
            filePath = fileURL.yp.string

            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        downloadRequest = AF.download(url, interceptor: nil, to: dest).downloadProgress(closure: { [weak self] (progressValue) in
            guard let weakSelf = self else { return }
            weakSelf.log("下载进度：\(progressValue.fractionCompleted)")
            progress?(progressValue.fractionCompleted)
        }).responseData { [weak self] (res) in
            guard let weakSelf = self else { return }
            filePath = filePath.yp.removeFileUrlPrefix()
            let videoCompatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(filePath)
            weakSelf.log("下载完成：\(filePath)")
            // 判断是否可以保存
            if videoCompatible {
                UISaveVideoAtPathToSavedPhotosAlbum(filePath, weakSelf, #selector(weakSelf.didFinishSavingVideo(videoPath:error:contextInfo:)), nil)
                weakSelf.log("保存完成")
            } else {
                failure?()
            }
        }
    }

    func cancel() {
        downloadRequest?.cancel()
    }

    // Fileprivate

    /// 日志系统
    fileprivate func log(_ log: String) {
        WmcLogManager.DebugLog(type: .downloadManager, log: log)
    }

    // Private

    /// 下载进度
    private var progressClosure: ((Double) -> Void)?

    /// 下载成功
    private var successClosure: (() -> Void)?

    /// 下载失败
    private var failureClosure: (() -> Void)?

    /// 下载任务
    private var downloadRequest: DownloadRequest?

    @objc
    private func didFinishSavingVideo(videoPath: String, error: NSError?, contextInfo: UnsafeMutableRawPointer?) {
        if error == nil {
            successClosure?()
        } else {
            failureClosure?()
        }
    }
}
